import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { getPermissionsList, getApplicationNameList, getAllSaaTask, deletePermissions, savePermissions } from "@/api/empower";
import { transformI18n } from "@/plugins/i18n";
import { ElMessage } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { useRoute, useRouter } from "vue-router";
export function useMenu() {
  const route = useRoute();
  const router = useRouter();
  const form = reactive({
    title: "",
    status: '',
    value1: '',
    taskCname: '',
    systemName: '',
    remark: '',
    validStatus: '',
  });
  let roleOptions = ref([])
  let roleOptions2 = ref([])
  const formRef = ref();
  const dataList = ref([]);
  let loading2 = ref(true);

  const getMenuType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "菜单" : "primary";
      case 1:
        return text ? "iframe" : "warning";
      case 2:
        return text ? "外链" : "danger";
      case 3:
        return text ? "按钮" : "info";
    }
  };

  const columns: TableColumnList = [
    {
      label: "权限名称",
      prop: "taskCname",
    },
    {
      label: "应用系统",
      prop: "systemName",
    },
    {
      label: "权限描述",
      prop: "remark"
    },
    {
      label: "状态",
      prop: "validStatus",
      align: "center",
      width: 100,
      slot: "validstatus"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,

  });
  let selectPag = reactive({
    total: 0,
    pageSize: 10,
    pageNum: 1,
    taskCode: "",//权限代码
    taskCname: "",//权限名称
    systemCode: "",//应用
    validStatus: '1', //状态
    startDate: "",
    endDate: "",
    value1: '',
  });
  let treeInfoRef = ref(null);
  let formVisible = ref(false);
  let formChild = ref({
    id: "",
    parentCode: "",
    taskCode: "",
    taskCname: "",
    systemCode: "",
    systemName: "",
    menuId: "",
    menuName: "",
    remark: "",
    powerType: "",
    childSysTasks: [],
    taskEname: "",
    createCode: "0000107",
    createName: "王曼霞",
    updateCode: null,
    updateName: null,
    validStatus: "1",
    enableFlag: null
  });
  //选择菜单
  const selectHandle = () => {
    treeInfoRef.value.dialogTree = true;
  };
  //取消添加子集
  const closeDialog = () => {
    formVisible.value = false;
  };
  //菜单
  const cropper = data => {
    formChild.value.menuId = data.checName;
    formChild.value.menuName = data.checName;
  };
  function onChange() {

  }
  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    selectPag.pageSize = val;
    selectPag.pageNum = 1
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    selectPag.pageNum = val
    onSearch();
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  async function onSearch() {
    loading2.value = true;
    const { data } = await getPermissionsList(selectPag);
    dataList.value = data.taskInfoVos.list;
    selectPag.total = data.taskInfoVos.totalSize;

    setTimeout(() => {
      loading2.value = false;
    }, 500);
  }
  function formatHigherMenuOptions(treeList) {
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].title = transformI18n(treeList[i].title);
      formatHigherMenuOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?) {
    if (title == '新增') {
      router.push({ name: 'powerAdd', query: { title: title } });
    } else {
      if (!row.parentCode || row.parentCode == "") {
        router.push({ name: 'powerAdd', query: { title: title, id: row.id } });
      } else {
        formChild.value = { ...formChild.value, ...row };
        formVisible.value = true
      }

    }
  }
  //保存子集同接口
  const submitSon = async () => {
    if (formChild.value.id && formChild.value.id != "") {
      formChild.value.id = formChild.value.id.toString();
    }
    let res = await savePermissions(formChild.value);
    if (res.code == 200) {
      onSearch();
      formVisible.value = false;
      ElMessage({
        message: res.msg,
        type: "success"
      });
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  };
  async function handleDelete(row) {
    let res = await deletePermissions({ id: row.id.toString() })
    if (res.code == 200) {
      ElMessage({
        message: res.msg,
        type: "success"
      });
      onSearch();
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  }
  function dataChange(value) {
    console.log(selectPag.value1);
    selectPag.startDate = selectPag.value1[0]
    selectPag.endDate = selectPag.value1[1]
    console.log(selectPag);

  }
  //获取应用系统
  const getgetApplicationNameList = async () => {
    let res = await getApplicationNameList();
    if (res.code == 200) {
      roleOptions.value = res.data;
    }
  };
  //获取权限
  const getgetAllSaaTask = async () => {
    let res = await getAllSaaTask({ systemCode: selectPag.systemCode })
    if (res.code == 200) {
      roleOptions2.value = res.data;
    }
  }
  const changesystem = () => {
    roleOptions2.value = []
    selectPag.taskCname = ''
    selectPag.taskCode = ''
    getgetAllSaaTask()
  }
  onMounted(() => {
    onSearch();
    getgetApplicationNameList()
  });

  return {
    submitSon,
    selectHandle,
    closeDialog,
    treeInfoRef,
    formVisible,
    formChild,
    cropper,
    changesystem,
    pagination,
    selectPag,
    dataChange,
    roleOptions,
    roleOptions2,
    form,
    loading2,
    columns,
    dataList,
    onChange,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange
  };
}
